/**
$Id: WsgiService.cpp 3096 2010-07-06 07:21:14Z Bear $

Copyright (c) 2010 Nuwa Information Co., Ltd, and individual contributors.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice,
     this list of conditions and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.

  3. Neither the name of Nuwa Information nor the names of its contributors
     may be used to endorse or promote products derived from this software
     without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

$Author: Bear $
$Date: 2010-07-06 15:21:14 +0800 (星期二, 06 七月 2010) $
$Revision: 3096 $
*/

#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>

#include <pion/net/HTTPResponseWriter.hpp>

#include "WsgiService.hpp"
#include "pion-glue.hpp"

#include "wsgi.h"

using namespace pion;
using namespace pion::net;

namespace pion {  // begin namespace pion
namespace plugins {  // begin namespace plugins

// WsgiService member functions
WsgiService::WsgiService() 
 : logger(PION_GET_LOGGER("pion.WsgiService")), info(false)  
{
}

WsgiService::~WsgiService() 
{
}

void WsgiService::setOption(const std::string& name, const std::string& value)
{
 if(name == "name") 
 {
  this->name = value;
 } 
 else if(name == "port") 
 {
  port = value;
 } 
#ifdef _PYTHON
#else
 else if(name == "module") 
 {
  module = value;
 } 
 else if(name == "app") 
 {
  app = value;
 } 
#endif
 else if(name == "info")
 {
  info = boost::lexical_cast<bool>(value);
 }
 else 
 {
  throw UnknownOptionException(name);
 }
}

#ifdef _PYTHON

void WsgiService::start()
{
}

void WsgiService::stop()
{
}

#else

void WsgiService::start()
{
 if(wsgiInit(module.c_str(), app.c_str(), "", ""))
  throw std::runtime_error("Unable to initialize WSGI.");
}

void WsgiService::stop()
{
 wsgiCleanup();
}

#endif

/// handles requests for WsgiService
void WsgiService::operator()(HTTPRequestPtr& request, TCPConnectionPtr& tcp_conn)
{
 HTTPResponseWriterPtr writer(HTTPResponseWriter::create(
  tcp_conn, *request, 
  boost::bind(&TCPConnection::finish, tcp_conn)));

 WsgiContext ctx(this, request, tcp_conn, writer);

 int error = wsgiHandler(&ctx);
 if(error)
  throw std::runtime_error("ERROR OCCURED IN wsgiHandler.");

 if(info)
 {
  boost::mutex::scoped_lock infoLock(infoMutex);

  std::string s("[THREAD:");
  s.append(boost::lexical_cast<std::string>(
#ifdef WIN32
   GetCurrentThreadId()
#else
   boost::this_thread::get_id()
#endif
  ));
  s.append("] ");
  s.append(request->getMethod());
  s.append(" ");
  s.append(request->getOriginalResource()); 

  const std::string& q = request->getQueryString();
  if(!q.empty())
  {
   s.append("?");
   s.append(q);
  } 

  s.append(" ");
  s.append(boost::lexical_cast<std::string>(
   writer->getResponse().getStatusCode()));
  s.append(" ");
  s.append(boost::lexical_cast<std::string>(ctx.sentBytes));

  PION_LOG_INFO(logger, s);
 } 

 if(request->getVersionString() == "HTTP/1.0")
 {
  writer->send();
 }
 else
 {
  writer->sendFinalChunk();

		tcp_conn->setLifecycle(TCPConnection::LIFECYCLE_CLOSE);
		tcp_conn->finish();
 }
}


} // end namespace plugins
} // end namespace pion


/// creates new WsgiService objects
extern "C" PION_SERVICE_API pion::plugins::WsgiService *pion_create_WsgiService(void)
{
 return new pion::plugins::WsgiService();
}

/// destroys WsgiService objects
extern "C" PION_SERVICE_API void pion_destroy_WsgiService(pion::plugins::WsgiService *service_ptr)
{
 delete service_ptr;
}
